<!-- 推广 -->
<template>
  <a-modal
    :visible="visible"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :footer="null"
    :closable="false"
    class="container"
    width="400px"
  >
    <div class="qrcode">
      <img :src="data.url" />
    </div>
    <div class="btn_group">
      <a-space :size="100">
        <a-button @click="handleCancel">关闭</a-button>
        <a-button type="primary" @click="downloadIamge">保存至电脑</a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script>
export default {
  name: "ProductCode",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {
        return {}
      }
    },
  },
  data() {
    return {

    }
  },
  created() {},
  methods: {
    handleCancel() {
      this.$emit('cancel')
    },
    // canvas 下载小程序码
    downloadIamge() {
      let imgsrc = this.data.url;
      let name = this.data.name;
      console.log(imgsrc, name);
      //下载图片地址和图片名
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        let canvas = document.createElement("canvas");
        console.dir(image)
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "金桔有品"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  text-align: center;
  .qrcode {
    margin-top: 20px;
    img {
      width: 200px;
      height: 200px;
      background: #aaa;
    }
  }
  .btn_group {
    margin-top: 35px;
    padding-bottom: 20px;
  }
}
</style>
